package com.etc.zzsys.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class AuthFilter
 */
/**
 * 
 * @author Administrator
 *
 */
//@WebFilter("/*")
public class AuthFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public AuthFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		System.out.println("AuthFilter doFilter");
		// TODO Auto-generated method stub
		// place your code here
		// 得到session对象 ,向将request对象转换为HttpServerletRequest
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 得到请求的uri地址
		String uri = req.getRequestURI();
		System.out.println("uri :" + uri);

		// req 相当于 servlet中的request
		HttpSession session = req.getSession();

		// 用户登录过
		if (session.getAttribute("users") != null) {
			// pass the request along the filter chain
			chain.doFilter(request, response);
		} else {

			// 用户访问的不是后台页面，而是登录页面 endsWith 以...结尾 ,放行我们的us.do的servlet
			if (uri.endsWith("html") || uri.endsWith("us.do")|| uri.endsWith(".css") || uri.endsWith(".js")) {
				chain.doFilter(request, response);
			} else {
				// 用户没登陆过,跳转到登录页面去
				res.sendRedirect("login.html");

			}

		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
